package com.googlecode.c4e.ui.views.internal;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.progress.IDeferredWorkbenchAdapter;
import org.eclipse.ui.progress.IElementCollector;

import com.googlecode.c4e.api.Registry;
import com.googlecode.c4e.api.model.Server;
import com.googlecode.c4e.ui.ContinuumPlugin;

public class ServerAdapter implements IDeferredWorkbenchAdapter {

	public Object[] getChildren(Object obj) {
		Server server = (Server) obj;
		if (server.getProjectGroups() != null) {
			return server.getProjectGroups().toArray();
		}
		try {
			server.setProjectGroups(Registry.getDefault().listProjectGroups(
					server));
		} catch (Exception e) {
			ContinuumPlugin.getDefault().log("listProjectGroups", e);
			return new Object[0];
		}
		return server.getProjectGroups().toArray();
	}

	public ImageDescriptor getImageDescriptor(Object arg0) {
		return ContinuumPlugin.getDefault().getImageDescriptor("continuum");
	}

	public String getLabel(Object obj) {
		Server server = (Server) obj;
		return server.getLabel();
	}

	public Object getParent(Object arg0) {
		return null;
	}

	public void fetchDeferredChildren(Object obj, IElementCollector collector,
			IProgressMonitor monitor) {
		Server server = (Server) obj;
		monitor.beginTask("Fetching projects for " + server.getLabel(), 100);

		if (server.getProjectGroups() != null) {
			monitor.done();
			collector.add(server.getProjectGroups().toArray(), monitor);
			return;
		}

		try {
			server.setProjectGroups(Registry.getDefault().listProjectGroups(
					server));
		} catch (Exception e) {
			monitor.done();
			throw new RuntimeException(e);
		}
		collector.add(server.getProjectGroups().toArray(), monitor);
		monitor.done();

	}

	public ISchedulingRule getRule(Object obj) {
		Server server = (Server) obj;
		return new ServerAdapterSchedulingRule(server);
	}

	public boolean isContainer() {
		return true;
	}

}
